package com.example.springdataelastci.config;

import com.google.common.collect.Maps;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * rabbitmsq 配置
 *
 * @author heyangyang
 * @since 2023-11-18
 */
@Configuration
public class RabbitmqConfig {

    /**
     * 延迟交换机 交换机配置
     */
    public static final String DELAYED_EXCHANGE = "delayed.exchange";

    /**
     * 队列
     */
    public static final String DELAYED_QUEUE = "delayed.queue";

    /**
     * routingKey
     */
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /**
     * 自定义延迟队列
     *
     * @return 交换机
     */
    @Bean("delayedExchange")
    public CustomExchange delayedExchange() {
        // 定义交换机类型
        Map<String, Object> args = Maps.newHashMap();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", Boolean.TRUE, Boolean.FALSE, args);
    }

    /**
     * 队列
     *
     * @return
     */
    @Bean("delayedQueue")
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE);
    }

    /**
     * 交换机和队列进行绑定
     *
     * @param delayedExchange 交换机
     * @param delayedQueue    队列
     * @return 绑定关系
     */
    @Bean
    public Binding delayedQueueBindingDelayedExchange(@Qualifier("delayedExchange") CustomExchange delayedExchange,
                                                      @Qualifier("delayedQueue") Queue delayedQueue) {
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}
